<!--
 * @Author: wuheng wuheng@szhbzc.com
 * @Date: 2025-01-02 14:31:00
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-03-03 17:37:38
 * @FilePath: \web-appc:\Users\wuheng\Desktop\WugangNew\src\centerViews\purchasing\purchasingplan\addPurchaasing\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="addPurchaasing">
    <pb-popup v-model="isVisible" @cancelFn="cancelFn" @confirmFn="confirmFn"
      :title="stutus == 'add' ? '新增供应商' : '编辑供应商'" Width="816">
      <div>
        <el-form :model="AddUpdataFrom" label-width="auto" :inline="true" :rules="AddUpdataFormRules"
          label-position="top" ref="ruleFormRef">
          <el-form-item label="供应商编号" prop="supplierCode">
            <pb-input v-model="AddUpdataFrom.supplierCode" placeholder="" :disabled="stutus != 'add'"
              @blur="checkCodeFn" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <pb-input v-model="AddUpdataFrom.supplierName" placeholder="" @blur="checkNameFn" />
          </el-form-item>
          <div class="nomargin">
            <el-form-item label="外部编码" class="mr-0">
              <pb-input v-model="AddUpdataFrom.externalCode" placeholder="" />
            </el-form-item>
          </div>
          <el-form-item label="联系人">
            <pb-input v-model="AddUpdataFrom.contact" placeholder="" />
          </el-form-item>
          <el-form-item label="电话">
            <pb-input v-model="AddUpdataFrom.phone" placeholder="" />
          </el-form-item>
          <el-form-item label="地址">
            <pb-input type="textarea" v-model="AddUpdataFrom.address" placeholder="" width="768px" maxlength="100"
              :showwordlimit="true" />
          </el-form-item>
          <el-form-item label="备注">
            <pb-input type="textarea" v-model="AddUpdataFrom.remark" placeholder="" width="768px" maxlength="100"
              :showwordlimit="true" />
          </el-form-item>
          <!-- <div :style="{ 'width': '100%' }"> -->
          <el-form-item label="资质">
            <div class=" flex upload">
              <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false"
                :on-change="handleFileChange1" accept="image/*, .dng, .DNG">
                <pb-icon name="tianjia" size="36" :color="'rgba(0, 0, 0, 0.45)'"></pb-icon>
              </el-upload>
              <div v-for="(img, index) in dishImg" :key="index" class="img-container">
                <img :src="img" class="dishImgs" alt="" v-if="img && img !== ''">
                <!-- <pb-button secondary size="small" class="delete-btn">
                  删除
                </pb-button> -->
                <pb-icon name="close" color="#fff" size="24" class="delete-btn" @click="deleteImage(index)"></pb-icon>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="uploadtext">
          最多上传2张不超过10M的JPG/PNG/JPEG
        </div>
        <div class="mt-6">
          <span class="labletext">供应单位</span>
          <span>
            <el-popover placement="top-start" :width="222" trigger="hover" effect="dark" content="同一个食堂可以绑定多个供应商">
              <template #reference>
                <pb-icon name="info" color="rgba(0,0,0,0.35)" class="ml-3 mt-0.5"></pb-icon>
              </template>
            </el-popover>
          </span>
        </div>
        <div class="flex bottombox">
          <el-checkbox v-for="(item, index) in checkboxlist" :key="index" v-model="item.checked"
            :label="item.tenantName" size="large" />
        </div>
      </div>
    </pb-popup>
  </div>
</template>
<script setup lang="ts">
import { AddPurchaseParamApi, EditPurchaseParamApi, GetkitchenListApi, GetCheckCodeExistApi, GetCheckNameExistApi } from '@/api/Purchasing'
import type { FormInstance } from 'element-plus'
import { GetFileProgressApi } from '@/api/upload'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
const ruleFormRef = ref<FormInstance>()
const deleteImage = (index) => {
  dishImg.value.splice(index, 1);
}
const dishImg = ref([] as any)
const selectedFile1 = ref<File | null>(null);
// 文件选择变化时的处理函数
const handleFileChange1 = (file: File) => {
  // 允许的文件类型
  const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/x-adobe-dng', 'image/webp'];
  // 允许的文件扩展名
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.dng', '.DNG', '.webp'];

  // 允许的最大文件大小，单位为字节，10MB = 10 * 1024 * 1024 字节
  const maxSize = 10 * 1024 * 1024;

  // 检查文件类型是否符合要求
  const isAllowedType = allowedMimeTypes.includes(file.type) || allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
  // 检查文件大小是否符合要求
  const isAllowedSize = file.size <= maxSize;

  if (isAllowedType && isAllowedSize) {
    selectedFile1.value = file;
    // 手动触发上传
    if (selectedFile1.value) {
      uploadFile1(selectedFile1.value);
    }
  } else {
    if (!isAllowedType) {
      createMessage({
        message: '不支持的文件格式，请上传图片文件。',
        type: 'error'
      })
    }
    if (!isAllowedSize) {
      createMessage({
        message: '文件大小超过限制，最大允许 10MB。',
        type: 'error'
      })
    }
  }
};

// 上传文件的函数
const uploadFile1 = async (file: any) => {
  const formData = new FormData();
  formData.append('file', file.raw);
  GetFileProgressApi(formData).then(res => {
    if (res.code == 2000) {
      if (dishImg.value.length >= 2) {
        dishImg.value.shift();
      }
      dishImg.value.push(res.data.fileUrl)
    }
  })
};
const isVisible = ref(false)
const stutus = ref('')
const checkCodeFn = () => {
  if (stutus.value != 'add' || AddUpdataFrom.supplierCode == '') return
  GetCheckCodeExistApi({
    "supplierId": 0,
    "supplierCode": AddUpdataFrom.supplierCode
  }).then((res: any) => {
    if (res.data.skuNameExist) {
      AddUpdataFormRules.value.supplierCode.push({
        validator: (rule, value, callback) => {
          callback(new Error('供应商编码不能重复！'));
        },
        trigger: 'blur'
      });
    } else {
      if (AddUpdataFormRules.value.supplierCode.length > 1) {
        AddUpdataFormRules.value.supplierCode.length = 1
      }
    }
  })
}
const checkNameFn = () => {
  GetCheckNameExistApi({
    "supplierId": stutus.value == 'add' ? 0 : AddUpdataFrom.supplierId,
    "supplierName": AddUpdataFrom.supplierName
  }).then((res: any) => {
    if (res.data.skuNameExist) {
      AddUpdataFormRules.value.supplierName.push({
        validator: (rule, value, callback) => {
          callback(new Error('供应商名称不能重复！'));
        },
        trigger: 'blur'
      });
    } else {
      if (AddUpdataFormRules.value.supplierName.length > 1) {
        AddUpdataFormRules.value.supplierName.length = 1
      }
    }
  })
}
let AddUpdataFrom = reactive({
  supplierCode: '',
  supplierName: '',
  externalCode: '',
  contact: '',
  phone: '',
  address: '',
  remark: '',
  // qualificationPic: '',
  supplyTenantIdList: [] as any
});
const emit = defineEmits(['getPurchasListfn'])
const checkboxlist = ref([] as any)
const AddUpdataFormRules = ref({
  supplierCode: [
    { required: true, pattern: /^\d{2,8}$/, message: '请输入2-8位数字', trigger: 'blur' }
  ],
  supplierName: [
    {
      required: true, pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]{1,24}$/,
      message: '请输入为 1 - 24 位的数字、字母或中文', trigger: 'blur'
    },
  ],
})
const cancelFn = () => {
  // AddUpdataFrom = purchFrom()
  clearObjKey(AddUpdataFrom)
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields(); // 重置表单并清除校验规则
  }
}
const clearObjKey = (clearForm: any) => {
  Object.keys(clearForm).forEach((key: any) => {
    if (Array.isArray(clearForm[key])) {
      // 如果属性是数组，则清空数组
      clearForm[key].length = 0;
    } else {
      // 如果属性不是数组，则设置为默认值（默认为空字符串）
      clearForm[key] = '';
    }
  });
}
const confirmFn = async () => {
  if (ruleFormRef.value) {
    await ruleFormRef.value.validate((valid) => {
      if (valid) {
        AddUpdataFrom.supplyTenantIdList.length = 0
        checkboxlist.value.map(ele => {
          if (ele.checked) {
            AddUpdataFrom.supplyTenantIdList.push(ele.tenantId)
          }
        })
        if (stutus.value == 'add') {
          AddPurchaseParamApi({ ...AddUpdataFrom, qualificationPicList: dishImg.value }).then(res => {
            if (res.code == 2000) {
              createMessage({
                message: '添加成功'
              })
              emit('getPurchasListfn')
              isVisible.value = false
            }
          })
        } else {
          EditPurchaseParamApi({ ...AddUpdataFrom, qualificationPicList: dishImg.value }).then(res => {
            if (res.code == 2000) {
              createMessage({
                message: '编辑成功'
              })
              emit('getPurchasListfn')
              isVisible.value = false
            }
          })
        }
      } else {
        // 处理验证错误
      }
    });
  }
}
const showFn = (row: any) => {
  // console.log(row, '222')
  GetkitchenListApi().then(res => {
    // console.log(res)
    checkboxlist.value = res.data
    checkboxlist.value.map(ele => {
      ele.checked = false
    })
    if (!row) {
      stutus.value = 'add'
    } else {
      // AddUpdataFrom = row
      Object.assign(AddUpdataFrom, row)
      dishImg.value = row.qualificationPicList ? row.qualificationPicList : []
      if (AddUpdataFrom.supplyTenantIdList == null) AddUpdataFrom.supplyTenantIdList = []
      stutus.value = 'updata'
      AddUpdataFrom.supplyTenantIdList.map((el: any) => {
        checkboxlist.value.map((check: any) => {
          if (check.tenantId == el) {
            check.checked = true
          }
        })
      })
    }
    isVisible.value = true
  })
}
defineExpose({ showFn })
</script>
<style lang="scss">
.addPurchaasing {
  .el-form-item--label-top .el-form-item__label {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
  }
}
</style>
<style lang="scss" scoped>
.addPurchaasing {
  .el-form-item {
    margin-right: 22px;
  }

  .nomargin {
    .el-form-item {
      margin-right: 0;
    }
  }

  .uploadtext {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.45);
  }

  .labletext {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
  }

  .avatar-uploader {
    width: 80px;
    justify-content: center;
    display: flex;
    height: 80px;
    background: rgba(0, 0, 0, 0.04);
  }

  .bottombox {
    flex-wrap: wrap;
  }

  .dishImgs {
    width: 100px;
    height: 100px;
    margin-left: 15px;
  }

  .img-container {
    position: relative;
    display: inline-block;
  }

  .delete-btn {
    position: absolute;
    top: 0;
    right: 0;
    display: none;
    /* 初始状态隐藏删除按钮 */
  }

  .img-container:hover .delete-btn {
    display: block;
    cursor: pointer;
    /* 鼠标悬停在容器上时显示删除按钮 */
  }
}
</style>
